const service = axios.create({
    baseURL: 'http://127.0.0.1:4523/mock/898702/api',
    timeout: 5000
})

service.interceptors.request.use(
    config => {
        if(!config.headers.Authorization){
            const token = localStorage.getItem('mobile_yy') ? JSON.parse(localStorage.getItem('mobile_yy')).token : ''
            config.headers.Authorization = 'Bearer '+ token
        }
        return config
    },
    error => {
        console.log(error) // for debug
        return Promise.reject(error)
    },
)

service.interceptors.response.use(
    response =>{
        const { code, data, msg} = response.data
        if (code === 200) {
            return data
        } else if (code === 50001) { // 鉴权失败
            vant.Toast('鉴权失败')
            location.href='./login.html'
            return Promise.reject('鉴权失败')
        } else {
            vant.Toast(msg || '网络请求错误')
            return Promise.reject(msg || '网络请求错误')
        }
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)
function $request(options) {
    options.method = options.method || 'get'
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data
    }

    return service(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach(item => {
    $request[item] = (url, data, options) => {
        return $request({
            url,
            data,
            method: item,
            ...options
        })
    }
})
